using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;
//using Microsoft.DirectX.Direct3D.CustomVertex;
//using Microsoft.DirectX.Generic;
using System.Threading;

namespace GraphicsAPIs
{
    public partial class DrawingCanvas : Form
    {
		private Device _device = null;
		public Device device
		{
			get { return _device; }
			set { _device = value; }
		}

		public DrawingCanvas()
		{
			InitializeComponent();
			this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
		}

		internal bool InitializeDevice()
		{
			try
			{
				PresentParameters presentParams = new PresentParameters();
				presentParams.Windowed = true;
				presentParams.SwapEffect = SwapEffect.Discard;
				device = new Device(0, DeviceType.Hardware, this.Handle,
						CreateFlags.SoftwareVertexProcessing, presentParams);
				return true;
			}
			catch (DirectXException)
			{
				MessageBox.Show("Failed to created the device");
				return false;
			}
			finally
			{
				device.Transform.Projection = 
					Matrix.PerspectiveFovLH( (float)Math.PI / 4,
											this.Width / this.Height, 1.0f, 100.0f);
				device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 5.0f), new Vector3(),
												 new Vector3(0, 1, 0));
				device.RenderState.Lighting = false;
				device.RenderState.CullMode = Cull.None;
			}
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			if (device == null) return;
			device.Clear(ClearFlags.Target, System.Drawing.Color.CornflowerBlue, 1.0f, 0);
			device.Present();
			VertexBuffer vb = new VertexBuffer(device, 3 *CustomVertex.PositionColored.StrideSize, Usage.None, VertexFormats.Transformed, Pool.Managed);
            CustomVertex.PositionColored[] verts = new CustomVertex.PositionColored[3];
            verts[0] = new CustomVertex.PositionColored(0f, 1f, 1f, Color.Red.ToArgb());
            verts[1] = new CustomVertex.PositionColored(-1f, -1f, 1f, Color.Green.ToArgb());
            verts[2] = new CustomVertex.PositionColored(1f, -1f, 1f, Color.Blue.ToArgb());
			GraphicsStream buf = vb.Lock(0, 3 * CustomVertex.PositionColored.StrideSize, LockFlags.None);
			buf.Write(verts);
			vb.Unlock();
			device.BeginScene();
            device.VertexFormat = CustomVertex.PositionColored.Format;
			device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, buf);
			device.EndScene();
			device.Present();
		}

		protected override void OnResize(EventArgs e)
		{
			Invalidate();
		}

    }
}